package cuttings;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Toolkit;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;
import java.awt.Cursor;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusListener;
import java.awt.event.FocusEvent;
import java.awt.Rectangle;

import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import java.util.Vector;

//opponents,gameplay,score managment
//assign words to opponents
//update score as letters entered
//display opponents names on list
//rewrite gameover

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Random;
import java.util.HashMap;
import java.util.Map;

import javax.swing.*;
import java.awt.*;


public class Game extends JPanel implements Runnable, Cuttings_Commons{ 

    private Dimension d;
    static private ArrayList opponents = new ArrayList();
    private Player player;
    //private Shot shot;

    private int opponentX = 200;
    private int opponentY = 5;

    private boolean ingame = true;
    
    //private final String expl = "images/explosion.png";
    private final String menuBanner = "images/haywards.png";
    private String message = "Game Over";
    	
    static JLabel teamscore_label = new JLabel("Team Score: 0");
    JTextField attack_field = new JTextField();	
	JLabel player_label = new JLabel("");
	
	//JLabel player_name_label = new JLabel("");
	JLabel team_label = new JLabel("Team:");
	JLabel opponent_label = new JLabel("Opponents");
	static JLabel oppscore_label = new JLabel("Opponent Score: 0");
	//JLabel time_label = new JLabel("Time:");
	JButton teamchat_button = new JButton("Team Chat");
	JButton globalchat_button = new JButton("Chat to All");
	JButton logout_button = new JButton("Log Out");
	JButton attack_button = new JButton("Attack!");
	static JLabel statusmsg_label4 = new JLabel(""); // status4
	static JLabel statusmsg_label3 = new JLabel(""); // status3
	static JLabel statusmsg_label2 = new JLabel(""); // status2
	static JLabel statusmsg_label1 = new JLabel(""); // status1
	
	static JLabel playerscore_label = new JLabel("Score: ");
	static JLabel score_label = new JLabel("0");
	static JLabel level_label = new JLabel("Level 0 - N00b");
	static JLabel lives_label = new JLabel("No. of Lives: 5");
	static JLabel charlimit_label = new JLabel("Char Limit: 10");
	
	static DefaultListModel listModel = new DefaultListModel();
	static JList opponent_list = new JList(listModel);	
	static JScrollPane opponent_scroll = new JScrollPane(opponent_list);

    private char letter ='\0';
    private int last_x=0,last_y=0;
    private String selListOppName = "";
    
	private String selMouseOppName="";
	private int selWordIndex=-1;

    private Thread animator;
    
    //queue/Arraylist of words
    //maintain state of player -> if not exists in map then player is dead
    
    static Map<String,Opponent> oppNameObjectMap = new HashMap<String,Opponent>();
    static Map<Integer,String> listPosNameMap = new HashMap<Integer,String>();
    
	static JTextField localChatMsg = new JTextField();
	static JTextField globalChatMsg = new JTextField();
	static final JComponent[] teamChatDialog = new JComponent[] {
					new JLabel("Team Chat"),
					localChatMsg
	};
	static final JComponent[] globalChatDialog = new JComponent[] {
					new JLabel("Chat to All"),
					globalChatMsg
	};	    
	
	static Vector<Integer> wordsx1 = new Vector<Integer>();
	static Vector<Integer> wordsx2 = new Vector<Integer>();	
	
	static private int numOfLives=5;
	static private int levelNum=0;
	static private String levelNumString= "";
	
	static private int pointsPerInter = 5;
	static private int charLimit = 10;
	
	static private boolean gotHit = false; 
	static private int prevScore =0;

    public Game() 
    {
		
		setLayout(null);
        addKeyListener(new TAdapter());
        addMouseListener(new Madapter());
        
        //addMouseMotionListener(new Madapter());

        
        d = new Dimension(GAME_WIDTH, GAME_HEIGHT);
        setBackground(Color.yellow);
        
        //setbounds (x,y,width,height)
        	
		player_label.setBounds(20, 20, 200, 20);
		add(player_label);
		
		playerscore_label.setBounds(650, 535, 200, 20);
		add(playerscore_label);		
		
		score_label.setBounds(700, 535, 200, 20);
		add(score_label);				
		
		level_label.setBounds(650, 520, 200, 20);
		add(level_label);		
		
		lives_label.setBounds(650, 502, 200, 20);
		add(lives_label);	
		
		charlimit_label.setBounds(650, 550, 200, 20);
		add(charlimit_label);			
		
		//player_name_label.setBounds(145, 20, 200, 20);
		//add(player_name_label);		
		
		team_label.setBounds(20, 35, 200, 20);
		add(team_label);				

		opponent_label.setBounds(20, 80, 200, 20);
		add(opponent_label);
		
		teamscore_label.setBounds(20, 320, 200, 20);
		add(teamscore_label);
		
		oppscore_label.setBounds(20, 350, 200, 20);
		add(oppscore_label);
		
		//time_label.setBounds(20, 380, 100, 20);
		//add(time_label);
		
		teamchat_button.setBounds(20, 380, 130, 20);
		add(teamchat_button);
		
		globalchat_button.setBounds(20, 410, 130, 20);
		add(globalchat_button);
		
		logout_button.setBounds(20, 440, 130, 20);
		add(logout_button);		
		
		opponent_scroll.setBounds(20,110,150,200);        	
		
		//attack_button.set
		
		statusmsg_label1.setBounds(200,43,300,20);
		statusmsg_label2.setBounds(200,30,300,20);
		statusmsg_label3.setBounds(200,15,300,20);
		statusmsg_label4.setBounds(200,0,300,20);
		
		attack_field.setBounds(200, GROUND+30, 300, 20);
		attack_button.setBounds(520, GROUND+30, 100, 20);
		
		
		add(attack_field);
		add(attack_button);
		add(opponent_scroll);
		add(statusmsg_label1);
		add(statusmsg_label2);
		add(statusmsg_label3);
		add(statusmsg_label4);
		
		opponent_list.addListSelectionListener(new OppListListener());
		opponent_list.addMouseListener(new Madapter()); // hack to remove focus
		
		teamchat_button.addActionListener(new ActionListener() {          
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, teamChatDialog, "Cuttings Game Session", JOptionPane.PLAIN_MESSAGE);				
				System.out.println("Team Chat: " + localChatMsg.getText());
				
				
				try {				
					UserRole.chatWithTeam(localChatMsg.getText());
				}catch (Exception ex){}		
				
				displayTeamChat("",localChatMsg.getText());
				requestFocusInWindow();  
			}
		}); 	
		
		globalchat_button.addActionListener(new ActionListener() {          
			public void actionPerformed(ActionEvent e) {
				JOptionPane.showMessageDialog(null, globalChatDialog, "Cuttings Game Session", JOptionPane.PLAIN_MESSAGE);				
				System.out.println("Global Chat: " + globalChatMsg.getText());
								
				
				try {				
					UserRole.chatWithParticipants(globalChatMsg.getText());
				}catch (Exception ex){}		
				
				
				displayGlobalChat("",globalChatMsg.getText());
				requestFocusInWindow();  
			}
		}); 
		
		logout_button.addActionListener(new ActionListener() {          
			public void actionPerformed(ActionEvent e) {
				
				
				try {				
					UserRole.logoutGame();
				}catch (Exception ex){}		
				
			}
		}); 		
		
		attack_button.addActionListener(new ActionListener() {          
			public void actionPerformed(ActionEvent e) {
				//player.publishFB(attack_field.getText());
				
				if(attack_field.getText().length() >0 && attack_field.getText().length() <=charLimit)
				{
					
					try {				
						UserRole.attackWithWord(attack_field.getText());
					}catch (Exception ex){}		
					
					//player.publishFB(attack_field.getText());
									
					attack_field.setText("");
					requestFocusInWindow();		
				}
				else
				{		
					JOptionPane.showMessageDialog(null, "You are limited to only " + charLimit + " characters",
						"Exceeded Word Limit", JOptionPane.INFORMATION_MESSAGE);
				}
			}
			
			 
		}); 
				
		setFocusable(true);
        gameInit();
        setDoubleBuffered(true);   
        
    }

    public void addNotify() {
        super.addNotify();
        gameInit();
        //updateOpponents(opponents);
    }
    
	static public void sendAttackWord(String u,String s)
	{
		displayStatus(u + " attacked with word: " + s);
	}        

    public void gameInit() {

        player = new Player();
        
        try {				
			player.set_name(UserRole.getMyName());
		}catch (Exception ex){}	
		
        try {				
			player.set_team(UserRole.getMyTeam());
		}catch (Exception ex){}	
					
        
        player_label.setText("Player Name: " + player.get_name());
        team_label.setText("Team: " + player.get_team());
        
        //shot = new Shot();
        
        requestFocusInWindow();  
        

        if (animator == null || !ingame) {
            animator = new Thread(this);
            animator.start();
        }
    }
    
    static public void resetGame()
    {
		oppNameObjectMap.clear();
        //listModel.clear();

        listPosNameMap.clear();
        opponent_list.removeAll();		
		
		wordsx1.clear();
		wordsx2.clear();
		
		numOfLives=5;
		levelNum=0;
		levelNumString= "Level 0 - N00b";
		
		pointsPerInter = 5;
		charLimit = 10;
		
		gotHit = false; 
		prevScore =0;		
		
		score_label.setText("0");
		level_label.setText("Level 0 - N00b");
		lives_label.setText("No. of Lives: "+numOfLives);
		charlimit_label.setText("Char Limit: "+charLimit);		
	}

    static public void updateOpponents(Vector<String> opp_list)
    {
		System.out.println("updateOpponents called!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
		
		
		//remove opponents in old list but not in updated sent list
		Iterator i4 = opponents.iterator();
		while (i4.hasNext()) {		
			Opponent a = (Opponent) i4.next();
			if(!opp_list.contains(a.getName()))
			{
				i4.remove();	
				oppNameObjectMap.remove(a.getName());
				System.out.println("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Removing opp_name " + a.getName());
			}
		}	
		
		for(int i=0;i<opp_list.size();i++)
		{
			String opp_name = opp_list.elementAt(i);
			if(!oppNameObjectMap.containsKey(opp_name))
			{
				Opponent opponent = new Opponent(opp_name);
				opponents.add(opponent);
				oppNameObjectMap.put(opponent.getName(),opponent);
				System.out.println("\n!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!Adding opp_name " + opp_name);
			}
		}
		
        Iterator i3 = opponents.iterator();
        
        listPosNameMap.clear();
        int ctr=0;
        listModel.clear();

        while (i3.hasNext()) {
            Opponent a = (Opponent) i3.next();
            listModel.addElement(a.getName());
            listPosNameMap.put(ctr,a.getName());
            ctr++;
        }  		
		
		/*
		for(int i=0;i<opp_list.size();i++)
		{
			String opp_name = opp_list.elementAt(i);
			System.out.println("Received in updateopponents: name is " + opp_name);
		}		
		
		for(int i=0;i<opp_list.size();i++)
		{
			String opp_name = opp_list.elementAt(i);
			
					
			if(!oppNameObjectMap.containsKey(opp_name))
			{
				Opponent opponent = new Opponent(opp_name);
				opponents.add(opponent);
			    oppNameObjectMap.put(opponent.getName(),opponent);
			    System.out.println("Adding opp_name " + opp_name);
			}
			else
			{
				Iterator i4 = opponents.iterator();

				while (i4.hasNext()) {		
					Opponent a = (Opponent) i4.next();
					if(a.getName().equals(opp_name))
					{
						i4.remove();
						System.out.println("Removing opp_name " + opp_name);
					}
				}
							
				oppNameObjectMap.remove(opp_name);
			}
        }		
        
        Iterator i3 = opponents.iterator();
        //listPosIDMap.clear();
        listPosNameMap.clear();
        int ctr=0;
        opponent_list.removeAll();

        while (i3.hasNext()) {
            Opponent a = (Opponent) i3.next();
            listModel.addElement(a.getName());
            //listPosIDMap.put(ctr,a.getID());
            listPosNameMap.put(ctr,a.getName());
            ctr++;
        }  		
        */
		
	}
	
    static public void displayAttack(String s,String opponentName)
    {
		
        Iterator i3 = opponents.iterator();

        while (i3.hasNext()) {
            Opponent a = (Opponent) i3.next();
            if(a.getName().equals(opponentName))
				a.addWord(s);
        }  		
		
	}	
	
	static public void rotateStatus() {
		statusmsg_label4.setText(statusmsg_label3.getText());
		statusmsg_label3.setText(statusmsg_label2.getText());
		statusmsg_label2.setText(statusmsg_label1.getText());
	}
	
	static public void displayStatus(String s) {
		rotateStatus();
		statusmsg_label1.setText(s);
	}
	
	static public void displayTeamChat(String u,String s) {
		displayStatus("(Team) " + u + " : " + s);
	}	
	
	static public void displayGlobalChat(String u,String s) {
		displayStatus("(All) " + u + " : " + s);
	}		
	
	static public void updateScore(int u,int t,int o) {
        int curScore = u;		
        prevScore = Integer.parseInt(score_label.getText().trim());
        
        score_label.setText(""+u);
        teamscore_label.setText("Team Score: " +t);
        oppscore_label.setText("Opponent Score: " +o);
		
		//level 1
		if(prevScore < 100 && curScore >= 100)
		{
			pointsPerInter = 10;
			//charLimit = 30;
			numOfLives++;
			levelNum = 1;
			displayStatus("Congratulations! You have reached level 1: The Speaker!");
		}
		
		//level 2
		if(prevScore < 250 && curScore >= 250)
		{
			pointsPerInter = 15;
			charLimit = 20;
			numOfLives+=1;
			levelNum = 2;
			displayStatus("Congratulations! You have reached level 2: The Debator!");
		}
		
		//level 3
		if(prevScore < 500 && curScore >= 500)
		{
			pointsPerInter = 20;
			charLimit = 30;
			numOfLives+=3;
			levelNum = 3;
			displayStatus("Congratulations! You have reached level 3: The Orator!");
		}
		
        updateStats();
	}
	
	static public void updateLevelString() {
		switch(levelNum)
		{
			case 0: levelNumString = "Level 0 - N00b"; break;
			case 1: levelNumString = "Level 1 - Speaker"; break;
			case 2: levelNumString = "Level 2 - Debater"; break;
			case 3: levelNumString = "Level 3 - Orator"; break;
		}
	}
	
	static public void updateStats() {
		updateLevelString();
        level_label.setText(levelNumString);
        lives_label.setText("Lives: " +numOfLives);
        charlimit_label.setText("Char Limit: " +charLimit);
	}
	

    public void drawPlayer(Graphics g) {
        if (player.isVisible()) {
            g.drawImage(player.getImage(), player.getX(), player.getY(), this);
            String test = "Leter Pressed:" + String.valueOf(letter);
            g.drawString(test,20,500);
        }

        if (player.isDying()) {
            player.die(); // kill the thread
            ingame = false;
        }
    }
     //if word is empty or word list is empty remove player id 
    // no no player is dead when server says so
    
	public static void eraseWord(int i,String s) {
        Iterator i3 = opponents.iterator();
        System.out.println("\n\n\n\n\n$$$$$$$$$$Erase word being called!$$$$$$$$$$\n\n\n\n");
        while (i3.hasNext()) {
            Opponent a = (Opponent) i3.next();
            //if(a.getID() == selectedOppID|| (a.getID()==selOpponentID)) // from mouse click
            if(a.getName().equals(s)) // from mouse click
            {
				ArrayList c = a.getWords();	// get words from that opponent
				
				Opponent.Weapon b = (Opponent.Weapon)c.get(i);
				b.setDestroyed(true);
			}
        }     
    }    

    public void updateWords(char LetterPressed) {
        Iterator i3 = opponents.iterator();
        while (i3.hasNext()) {
            Opponent a = (Opponent) i3.next();
            //if(a.getID() == selectedOppID|| (a.getID()==selOpponentID)) // from mouse click
            if(a.getName().equals(selListOppName) || a.getName().equals(selMouseOppName)) // from mouse click
            {
				ArrayList c = a.getWords();	// get words from that opponent
				
				for (int i = 0; i < c.size(); i++) {
					Opponent.Weapon b = (Opponent.Weapon)c.get(i);
					//System.out.println("b val is " + c.size());
					//g2d.drawImage(m.getImage(), m.getX(), m.getY(), this);
					
					if(selWordIndex!=-1 && i!=selWordIndex) 
						continue;
					
					if(!b.isDestroyed())
					{
						
						int letter_score = b.removeLetter(LetterPressed);
						
						// word was succesfully intercepted
						if(letter_score==10) 
						{
							//updateInterceptedWord(player.get_name(),player.get_team(),!player.get_team());
							
							
							try {				
								//UserRole.interceptedWord(i,a.getName(),5);
								UserRole.interceptedWord(i,a.getName(),pointsPerInter);
							}catch (Exception ex){}		
							b.setDestroyed(true);
							//update levels
							
						}
						
						//System.out.println("letter score is " + letter_score);
					}
				}
			}
        }     
    }

	
	public void broadcastMessage(String n,boolean t,String m)
	{
		statusmsg_label1.setText(n + " from " + t + " says: " + m);
	}
    
	public void updateInterceptedWord(String n,boolean t,boolean o)
	{
		statusmsg_label1.setText(n + " from team " + t + " intercepted word from team "+o);
	}
    
    public void drawWeaponing(Graphics g) {
        Iterator i3 = opponents.iterator();

        while (i3.hasNext()) {
            Opponent a = (Opponent) i3.next();
            
			ArrayList c = a.getWords();	// get words from that opponent
				
			for (int i = 0; i < c.size(); i++) {
				Opponent.Weapon b = (Opponent.Weapon)c.get(i);
					
				//g2d.drawImage(m.getImage(), m.getX(), m.getY(), this);            
				//Opponent.Weapon b = a.getWeapon();

				if (!b.isDestroyed()) {
					if((a.getName().equals(selListOppName)&&i==selWordIndex) || (a.getName().equals(selMouseOppName)&&i==selWordIndex)) // from mouse click
					{
						Font small = new Font("Ariel", Font.BOLD, 20);
						g.setFont(small);					
					}
					else
					{
						Font small = new Font("Helvetica", Font.BOLD, 14);
						g.setFont(small);	
					}
					
					//if(c.size()==2)
					//{
						//System.out.println(b.getWord());
					//}
					
					g.drawString(b.getWord(),b.getX(),b.getY());
				}
			}
        }
    }

    public void paint(Graphics g)
    {
        super.paint(g);           
		
		if(ingame) {
            g.drawLine(180, 60, GAME_WIDTH, 60);
            
            //drawing line
            g.drawLine(180, GROUND, GAME_WIDTH, GROUND);
            drawPlayer(g);
            drawWeaponing(g);               
            
            /*
			//draw holes
			g.setColor(Color.yellow);
			for(int i=0;i<wordsx1.size();i++)
				g.drawLine(wordsx1.get(i), GROUND, wordsx2.get(i), GROUND);  		
            g.setColor(Color.black);
            */
            
			g.setColor(Color.yellow);

			for(int j=0;j<5;j++)
			{
				if(j>0) g.setColor(Color.red);
				for(int i=0;i<wordsx1.size();i++)
					g.drawLine(wordsx1.get(i), GROUND+j, wordsx2.get(i), GROUND+j);       
			}
			g.setColor(Color.yellow);        
            //updateScore();
        }

        Toolkit.getDefaultToolkit().sync();
        g.dispose();
    }
 
	/*
    public void gameOver()
    {

        Graphics g = this.getGraphics();

        g.setColor(Color.blue);
        //setBackground(Color.yellow);
        g.fillRect(0, 0, GAME_WIDTH, GAME_HEIGHT);

        g.setColor(new Color(0, 32, 48));
        g.fillRect(50, GAME_WIDTH/2 - 30, GAME_WIDTH-100, 50);
        g.setColor(Color.white);
        g.drawRect(50, GAME_WIDTH/2 - 30, GAME_WIDTH-100, 50);

        Font small = new Font("Helvetica", Font.BOLD, 14);
        FontMetrics metr = this.getFontMetrics(small);

        g.setColor(Color.white);
        g.setFont(small);
        g.drawString(message, (GAME_WIDTH - metr.stringWidth(message))/2, 
                GAME_WIDTH/2);
    }
    */

	//where the words positions are dropped
    public void animationCycle()  {

        // player
        if(ingame)
        {
            //player.act();
            // weapons
            
            Iterator i3 = opponents.iterator();
            Random generator = new Random();

            while (i3.hasNext()) {
                int shot = generator.nextInt(15);
                Opponent a = (Opponent) i3.next();
                
				ArrayList c = a.getWords();	// get words from that opponent
				
				for (int i = 0; i < c.size(); i++) {
					Opponent.Weapon b = (Opponent.Weapon)c.get(i);                

					int weaponX = b.getX();
					int weaponY = b.getY();
					int playerX = player.getX();
					int playerY = player.getY();

					//weapon hits player

					if (player.isVisible() && !b.isDestroyed()) {
						/*
						if ( weaponX >= (playerX) && 
								weaponX <= (playerX+player.getWidth()) &&
								weaponY >= (playerY) && 
								weaponY <= (playerY+player.getHeight()) ) 
						*/
						if(b.getBounds().intersects(player.getBounds()))
						{
							
							numOfLives--;
							displayStatus("You lost a life! Number of lives left is " + numOfLives);
							//send global chat
							System.out.println("word that killed player was " + b.getWord());
							updateStats();
							
							if(numOfLives==0)
							{
								player.setDying(true);
								
								
								try {			
									UserRole.lifeZero();
								}catch (Exception ex){}		
															
								
								//Menu.endGame("lose");
							}
							b.setDestroyed(true);							
						}
					}
					
					if(!b.isDestroyed() && (b.getWord().length()>0)) // check for empty string
					{
						//System.out.println("b dropping word is " + b.getWord());
						b.setY(b.getY() + 1);    // updated position of words.
						if (b.getY() >= GROUND) {
							System.out.println("word that dropped on floor was " + b.getWord());
							
							wordsx1.add(b.getX());
							wordsx2.add(b.getX()+(b.getWord().length()*10));
							try {				
								//UserRole.interceptedWord(i,a.getName(),5);
								UserRole.wordMissed(a.getName());
							}catch (Exception ex){}	
							b.setDestroyed(true);		
						}		
					}
					
				}
            }
        }
    }

    public void run() {

        long beforeTime, timeDiff, sleep;

        beforeTime = System.currentTimeMillis();

        while (ingame) {
            repaint();
            animationCycle();   
            
            timeDiff = System.currentTimeMillis() - beforeTime;
            sleep = DELAY - timeDiff;
            
            if (sleep < 0) 
                sleep = 2;
                
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                System.out.println("interrupted");
            }
            beforeTime = System.currentTimeMillis();
        }
        //gameOver();
    }
     
	private class OppListListener implements ListSelectionListener {
		public void valueChanged(ListSelectionEvent evt) {
			if (evt.getValueIsAdjusting())
			  return;
			
			JList list = (JList) evt.getSource();
			int selections[] = list.getSelectedIndices();
			Object selectionValues[] = list.getSelectedValues();
			System.out.println("Selected "+selections[0]);
			selListOppName = listPosNameMap.get(selections[0]);
			  
			Iterator i3 = opponents.iterator();
			while (i3.hasNext()) {            
				Opponent a = (Opponent) i3.next();
				if(a.getName().equals(selListOppName))
				{
					ArrayList c = a.getWords();	// get words from that opponent
					selWordIndex=-1;
					for (int i = 0; i < c.size(); i++) {
						Opponent.Weapon b = (Opponent.Weapon)c.get(i);  
						if(!b.isDestroyed())
						{
							selWordIndex = i;
							break;
						}
					}	
				}		  
			  
			}
			
			selMouseOppName = "";			
			
		}		
	}     
		
	/*
	private class OppListListener implements ListSelectionListener {
		public void valueChanged(ListSelectionEvent evt) {
			if (evt.getValueIsAdjusting())
			  return;
			
			//selectedOppID = listPosIDMap.get(evt.getLastIndex());
			selListOppName = listPosNameMap.get(evt.getLastIndex());
			System.out.println("Selected from " + evt.getFirstIndex() + " to " + evt.getLastIndex()+" " +selListOppName);			
			//selOpponentID = -1;
			selMouseOppName = "";
		  }		
	}
	*/
	
    private class TAdapter extends KeyAdapter {

        public void keyReleased(KeyEvent e) {
            player.keyReleased(e);
        }

        public void keyPressed(KeyEvent e) {
            player.keyPressed(e,wordsx1,wordsx2);
            letter = e.getKeyChar();
            updateWords(letter);
            player.act();
        }
    }

    private class Madapter extends MouseAdapter {

        public void mouseClicked(MouseEvent e){
            last_x = e.getX();
            last_y = e.getY();
 
			Iterator i3 = opponents.iterator();
			while (i3.hasNext()) {            
				Opponent a = (Opponent) i3.next();
            
				ArrayList c = a.getWords();	// get words from that opponent
				
				for (int i = 0; i < c.size(); i++) {
					Opponent.Weapon b = (Opponent.Weapon)c.get(i);  
					
					if(!b.isDestroyed())
					{
						//if((last_x >= b.getX()-40 && last_x <= b.getX()+40) &&(last_y >= b.getY()-5 && last_y <=b.getY() + 5)) 
						if((last_x >= b.getX()-10 && last_x <= b.getX()+10*b.getWord().length()) &&(last_y >= b.getY()-10 && last_y <=b.getY() + 15)) 
						{
							System.out.println("Selected word is " + b.getWord());
							
							//selOpponentID = a.getID();
							selMouseOppName = a.getName();
							selWordIndex = i;
							
							//selectedOppID =-1;
							selListOppName = "";
							System.out.println("wordindex is " + selWordIndex);
						}
					}
				
				}
			}	   
            requestFocusInWindow();  
            
        }
    }

}
